package com.irdstudio.efp.nls.service.impl.ms;

import java.util.*;
import java.util.concurrent.*;


import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.irdstudio.basic.framework.core.util.GsonUtils;
import com.irdstudio.efp.nls.common.util.KafkaUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.esb.service.vo.BigShowVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.esb.common.constant.MsLoanConstant;
import com.irdstudio.efp.esb.service.bo.req.MsLoanReq;
import com.irdstudio.efp.esb.service.bo.resp.MsLoanResp;
import com.irdstudio.efp.esb.service.facade.MsLoanService;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.impl.SoltServiceImpl;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 
 * 马上贷款审核通知接口（广州银行->马上）节点
 * 
 * @author ludayong
 * @since 2018年12月28日 上午9:34:42
 * @version 1.0
 */
@Service("msLoanApprNoticeService")
public class MsLoanApprNoticeServiceImpl extends SoltServiceImpl {

	private static Logger logger = LoggerFactory.getLogger(MsLoanApprNoticeServiceImpl.class);

	@Autowired
	@Qualifier("msLoanService")
	private MsLoanService msLoanService;// 马上贷款审核通知

	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;// 网贷申请基本信息

	// kafka主机IP地址
	// kafka端口号
	@Value("${bigshow.servers}")
	private String servers;

	// kafka发送的主题topic
	@Value("${bigshow.kafkaToptic}")
	private String kafkaToptic;

	@Override
	protected void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
		String applySeq = nlsProcessBizVo.getApplySeq();// 流水号

		try {
			logger.info("马上贷款审核通知接口（广州银行->马上），流水号:" + applySeq);
			Objects.requireNonNull(nlsApplyInfoVO);// 网贷申请信息不能为空

			String nlsApplyState = Objects.requireNonNull(nlsApplyInfoVO.getNlsApplyState());// 审批状态（网贷贷款申请状态）

			try {
				MsLoanReq msLoanReq = new MsLoanReq();
				msLoanReq.setTxnFlowNo(applySeq);// 交易流水号

				boolean isSend = false;// 是否发送通知请求

				nlsApplyInfoVO.setRefuseCause("");//清空拒绝原因
				nlsApplyInfoVO.setDnSts(MsLoanConstant.DN_STS_3);// 放款状态

				logger.info("马上贷款审核通知更新放款状态信息：" + JSONObject.toJSONString(nlsApplyInfoVO));
				int num = nlsApplyInfoService.updateByPk((nlsApplyInfoVO));
				logger.info("马上贷款审核通知更新放款状态信息：" + JSONObject.toJSONString(num));

				msLoanReq.setAudRslt(MsLoanConstant.AudRsltEnum.PASS.VALUE);

				//能执行到这个插槽服务，证明审批是通过的
				// if (MsLoanConstant.NlsApplyStateEnum.REJECT.VALUE.equals(nlsApplyState)
				// || MsLoanConstant.NlsApplyStateEnum.CANCEL.VALUE.equals(nlsApplyState)) {//
				// 拒绝或者取消
				// msLoanReq.setAudRslt(MsLoanConstant.AudRsltEnum.REJECT.VALUE);
				// msLoanReq.setRfsRsn(queryNlsApplyInfoVO.getRefuseCause());// 拒绝原因
				// }

				if (num > 0) {
					isSend = true;
				}
				if (isSend) {// 发送请求
					MsLoanResp msLoanResp = msLoanService.msLoan(msLoanReq);// 发送请求
					try {
						Objects.requireNonNull(msLoanResp);
						if (!MsLoanConstant.RetCodeEnum.SUCCESS.VALUE.equals(msLoanResp.getRetStCd())) {// 0：请求成功，其他编码均代表失败
							logger.error("调用马上审批结果消费接口返回信息" + msLoanResp.getRtnMsg());
						}
						//风控大屏展示-马上进件的每一笔都要发送数据过去，不管是否发送成功，都不影响马上进件 dengqiwen 20200415
						try {
							if (MsLoanConstant.RetCodeEnum.SUCCESS.VALUE.equals(msLoanResp.getRetStCd())) {
								logger.info("马上审批结果消费接口调用成功，发送kafka消息给大数据开始");
								BigShowVO array =new BigShowVO();
								array.setSysName("网贷");
								array.setCreditNo(applySeq);
								array.setCreditAmount(nlsApplyInfoVO.getApplyAmt());
								array.setProductName(nlsApplyInfoVO.getPrdName());
								array.setName(nlsApplyInfoVO.getCusName());
								array.setCertNo(nlsApplyInfoVO.getCertCode());
								array.setPhoneNum(nlsApplyInfoVO.getMobile());
								//数据日期
								String timeStamp = TimeUtil.getTimeStampByPattern("yyyyMMdd HH:mm:ss");
								array.setDateTime(timeStamp);
								//把对象装进list在用map.put的原因是因为要满足大数据对json报文的格式要求
								List<BigShowVO> jsonObjects = new ArrayList<BigShowVO>();
								jsonObjects.add(array);
								Map<String,Object> map = new HashMap<String,Object>();
								map.put("array",jsonObjects);
								//单例线程池
								ThreadFactory threadFactoryBuilder = new ThreadFactoryBuilder().setNameFormat("ms-bigShow-singleThreadPool").build();
								ThreadPoolExecutor singleThreadPool = new ThreadPoolExecutor(1,1,0L,
										TimeUnit.MICROSECONDS,new LinkedBlockingDeque<Runnable>(1024),
										threadFactoryBuilder,new ThreadPoolExecutor.AbortPolicy());
								singleThreadPool.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        KafkaUtil kafka=new KafkaUtil(servers,kafkaToptic);
                                        try {
                                            kafka.sendMessage(GsonUtils.toJson(map));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            logger.error("马上进件申请交易，发送kafka消息给大数据失败，申请流水号："+applySeq+"，异常信息：" + e.getMessage());
                                        }

                                    }
                                });
								singleThreadPool.shutdown();
								logger.info("马上审批结果消费接口调用成功，发送kafka消息给大数据结束，申请流水号："+applySeq);
							}
						} catch (Exception e) {
							logger.error("马上审批结果消费接口调用成功，发送kafka消息给大数据异常，申请流水号："+applySeq+"，异常信息：" + e.getMessage());
						}
					} catch (Exception e) {
						nlsProcessBizVo.setExceptionFlag(true);
						nlsProcessBizVo.setExceptionMsg(e);
						logger.error("调用马上审批结果消费接口出现异常：" + e.getMessage());
						throw new BizException("系统异常", e);
					}
				}
			} catch (Exception e) {
				nlsProcessBizVo.setExceptionFlag(true);
				nlsProcessBizVo.setExceptionMsg(e);
				logger.error("调用马上审批结果消费接口出现异常：" + e.getMessage());
				throw new BizException("系统异常", e);
			}
		} catch (Exception e) {
			logger.error("马上贷款审核通知出现异常：" + e.getMessage());
			nlsProcessBizVo.setExceptionFlag(true);
			nlsProcessBizVo.setExceptionMsg(e);
		}
	}
}
